<template>
  <div>
    <!-- 索赔结算单查询-详情页面 -->
    <BreakSpace label="结算单信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel ref="formPanel" :list="formList" :cols="3" :formType="'add'" labelWidth="110" :isSubmitBtn="false" @formChange="formChangeHandle" />
    <div style="padding-top: 3rem"></div>
    <BreakSpace label="索赔信息" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      ref="table"
      :dataSource="dataList"
      :columns="columns"
      :params="fetchParams"
      :datakey="'data'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectChange"
      :isPagination="false"
      :isSelectColumn="false"
      :isServerSorter="false"
      :isServerFilter="false"
      :isToperInfo="false"
      :isColumnFilter="false"
      height="auto"
      :is-select-column="false"
    >
    </FilterTable>
    <FilterTable
      ref="table2"
      :isColumnFilter="false"
      :isSelectColumn="false"
      :isToperInfo="false"
      :isServerSorter="false"
      :isServerFilter="false"
      :dataSource="reportInfo"
      :isPagination="false"
      :columns="columnsReport"
      :params="fetchParams"
      :datakey="'data'"
      :onColumnsChange="columnsReport => (this.columnsReport = columnsReport)"
      :onRowSelectChange="selectChange"
      height="auto"
    >
    </FilterTable>
    <BreakSpace label="发票信息" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      ref="invoiceInfo"
      :dataSource="invoiceInfo"
      :columns="columnsInvoice"
      :datakey="'data'"
      :onColumnsChange="columnsInvoice => (this.columnsInvoice = columnsInvoice)"
      :onRowSelectChange="selectChange"
      :isPagination="false"
      :isSelectColumn="false"
      :isServerSorter="false"
        :isServerFilter="false"
        :isToperInfo="false"
        :isColumnFilter="false"
      height="auto"
      :is-select-column="false"
    ></FilterTable>
    <BreakSpace label="附件信息" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
          ref="fileTable"
          :columns="columnsFile"
          columnsRef="whbydUploadFile"
          :isSelectColumn="false"
          :onColumnsChange="columnsFile => (this.columnsFile = columnsFile)"
          height="auto"
        />
     <BreakSpace label="签收记录" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
          ref="auditHistoryTable"
          :columns="columnsAuditHistory"
          columnsRef="auditHistory"
          :isSelectColumn="false"
          :onColumnsChange="columnsAuditHistory => (this.columnsAuditHistory = columnsAuditHistory)"
          height="auto"
        />
    <div style="padding-top: 3rem"></div>

    <!-- 物流信息 -->
    <BreakSpace label="物流信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel
      ref="logisticsPanel"
      :list="logisticsList"
      :cols="4"
      :formType="'add'"
      labelWidth="110"
      :isSubmitBtn="false"
      @formChange="formChangeHandle"
    />
    <div style="padding-top: 3rem"></div>
    <BreakSpace label="驳回意见" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel ref="formPanelAudit" :list="formAuditList" :cols="1" :formType="'add'" labelWidth="110" :isSubmitBtn="false" @formChange="formChangeHandle" />
    <el-button type="primary" @click="auditPass" >签收</el-button>
    <el-button type="primary" @click="auditNoPass" >驳回</el-button>
    <el-button type="primary" @click="closeDialog">关 闭</el-button>
    <!-- <BasePrint ref="templateSettleBils" :data="printList" template="waitReturnLabel/templateSettleBils"/> -->
  </div>
</template>
<script>
import { isFormEmpty } from '@/utils/index';
import { getCloseAccountCount, getPartType,getClaimInfoByNo,getCostCountByNo,editSave,quyrpBatch,updateBusinessMoney,getCbClaim } from '@/api/claim/factory/ClaimStatementQueryFactory';
// import { getCloseAccountCount, getPartType, getClaimInfoByNo, getCostCountByNo } from '@/api/coordinate/claimSettleClose';
// import { approve,quyrpBatch} from '@/api/claim/factory/ClaimInvoiceCheck';
import { dictionary } from '@/utils/dictMixin';
//import uploadFile from "@/pages/coordinate/claimDemage/BasicData/ClaimInvoiceCheck/uploadFile";
// import { getClaimAccountInfo,auditInvoiceResult,queryAuditHistory} from '@/api/claim/factory/claimStatamentInvoiceAudit';
import { getCodeType, queryClaimPageInfoBySettleNo,auditInvoiceResult, queryClaimInvoiceInfoBySettleNo,queryLogisticsInfoBySettleNo,queryInvoiceType,queryFileInfoBySettleNo,getAuditHistory} from '@/api/claim/factory/claimStatamentInvoiceAudit';
import config from '@/assets/js/config';
import { findFileByUrl } from '@/api/partsmanage/financialManagement/capitalAccount/index'
export default {
  mixins: [dictionary],
  props: ['rowData'],
  components: {
    //uploadFile
  },
  data() {
    return {
      dataList: [],
      reportInfo: [],
      invoiceInfo: [],
      dataList1: [],
      kaohesum: 0,
      suopeisum: 0,
      huanxiajiandataList: [],
      fujiaxiangmudataList: [],
      openPartSettleSubmitPage: false,
      //索赔单列表开关
      suopeidanFlag: false,
      kaohedanFlag: false,
      visibleDrawer: false,
      collapse: false,
      infoId: null,
      printList: {
        rows: [
          {
          }
        ]
      },
      flterValue: {}, //参数
      columns: this.creatHeader(),
      columnsReport:this.creatHeaderReport(),
      columnsInvoice: this.creatInvoiceTable(),
      //withholdColumns: this.creatWithholdHeader(),
      //columns1: this.creatHeader1(),
      //columns2: this.creatHeader2(),
      //columns3: this.creatHeader3(),
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中经销商
      formList: this.createFormList(),
      formAuditList: this.createAuditFormList(),
      columnsFile: this.createdFileTable(),
      columnsAuditHistory: this.createdAuditHistoryTable(),
      logisticsList: this.createLogisticsList(),
      editRow: {},
      saveData: null,
      upVisible: false,
      assessId: null
    };
  },
  created() {
    this.findBuyItems();
    this.tableInfo();
    this.claimTableInfo();
    this.queryInvoiceTypeInfo();
    this.queryFileInfo();
    this.queryLogisticsInfo();
    this.queryAuditHistoryInfo();
  },
  methods: {
    formChangeHandle(val) {
      this.saveData = val;
    },
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = Object.assign({}, this.fetchParams, val);
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
    },
    async claimTableInfo() {
      let data = {};
      let res = await queryClaimPageInfoBySettleNo(this.rowData.settleNo);
      console.log('===================' + JSON.stringify(res) + 'res++++++++++++++++');
      //为table赋值(索赔单)
      if (200 == res.resultCode) {
        data = res.data;
        if (isFormEmpty(data)) {
          data = {};
        }
        this.$refs.table.$refs.pageTable.EXECUTE_INSERT(data);
      }
    },
    async tableInfo() {
      const res = await getCodeType({ type: 5010 });
      if (res.resultCode == 200) {
        this.columnsReport.find(x => x.dataIndex == 'invoiceType').initialValue = '';
        this.columnsReport.find(x => x.dataIndex == 'invoiceType').editItems = res.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
      }
    },
    async queryInvoiceTypeInfo(){
        //开票信息
        let invoiceData = null;
        let resData = await queryInvoiceType(this.rowData.settleNo);
        if (200 == resData.resultCode) {
          invoiceData = resData.data;
          this.$refs.table2.$refs.pageTable.EXECUTE_INSERT(invoiceData);
        }
    },
    async queryFileInfo(){
        //查询附件信息
        let resData = await queryFileInfoBySettleNo(this.rowData.settleNo);
        if(resData.resultCode == 200){
          this.$refs.fileTable.$refs.pageTable.EXECUTE_INSERT(resData.data);
        }
    },
    async queryAuditHistoryInfo(){
        //查询审核信息
        let resData = await getAuditHistory(this.rowData.settleNo);
        if(resData.resultCode == 200){
          this.$refs.auditHistoryTable.$refs.pageTable.EXECUTE_INSERT(resData.data);
        }
    },
    async queryLogisticsInfo(){
        //查询物流信息
        let logisticsData = null;
        let resData = await queryLogisticsInfoBySettleNo(this.rowData.settleNo);
        if (200 == resData.resultCode) {
          logisticsData = resData.data;
          this.logisticsList.map(a =>{
              a.initialValue = logisticsData[a.fieldName];
          })
        }
    },
      //给input框赋值
    async findBuyItems() {
      this.formList.map(x => {
        if (x.fieldName == 'finalStatementType') {
          x.initialValue = this.createDictText(this.rowData[x.fieldName], '5002');
        } else {
          x.initialValue = this.rowData[x.fieldName];
        }
      });

      let data = {};
      let res = await queryClaimInvoiceInfoBySettleNo(this.rowData.settleNo);
      //为table赋值(索赔单)
      if (200 == res.resultCode) {
        data = res.data;
        if (isFormEmpty(data)) {
          data = {};
          this.invoiceTableInfo = [
            {
              batteryMaintenanceId: 0,
              invoiceBatchNumber: '',
              invoiceNumber: '',
              money: '',
              taxes: '',
              amount: '',
              invoiceDate: ''
            }
          ];
        }
        this.$refs.invoiceInfo.$refs.pageTable.EXECUTE_INSERT(data);
      }
      //   }
      //   //为抵扣单赋值
      //   let res4 = await getCbClaim(this.rowData.settleNo);
      //   if (200 == res4.resultCode) {
      //     let diKouData = res4.data;
      //     if (isFormEmpty(diKouData)) {
      //       diKouData = {};
      //     }
      //     this.$refs.withholdTable.$refs.pageTable.EXECUTE_INSERT(diKouData);
      //   }
    },

    auditPass(){
      let data=this.$refs.formPanelAudit.SUBMIT_FORM();
      
      let params={
          checkRemarks:data.checkRemarks,
          auditType:'success',
          settleNo:this.rowData.settleNo
      }
        auditInvoiceResult(params).then(res => {
          if(res.resultCode == 200){
                    this.$message({
                    type: 'success',
                    message: '操作成功!'
                  });
                  // 重新加载
                  this.closeDialog();
              }
          
        })
    },
    auditNoPass(){
      let data=this.$refs.formPanelAudit.SUBMIT_FORM();
      if(data.checkRemarks!=null&&data.checkRemarks!=""&&data.checkRemarks!="undefined"){
        let params={
          checkRemarks:data.checkRemarks,
          auditType:'fail',
          settleNo:this.rowData.settleNo
        }
        auditInvoiceResult(params).then(res => {
          if(res.resultCode == 200){
                    this.$message({
                    type: 'success',
                    message: '操作成功!'
                  });
                  // 重新加载
                  this.closeDialog();
              }
          
        })
      }else{
        this.$message({
                    type: 'warning',
                    message: '请填写驳回意见!'
                  });
      }
      
    },

    //取消操作
    closeDialog() {
      this.$emit('close', { openPartSettleSubmitPage: false, data: this.selectedRows, type: 'close' });
    },
    editFile(row) {
      this.upVisible = true;
      this.assessId = row.assessId;
    },
    chooseOrderNo() {
      this.openPartSettleSubmitPage = true;
    },
     // 获取服务端文件 to blob
    async downLoadByUrl(url, params = {}) {
      let res = await findFileByUrl(url);
      console.log(res.data)
      return res.data;
    },
    // 执行下载动作
    async downloadFile(url) {
      console.log(url)
      const data = await this.downLoadByUrl(url);
      console.log('downloadUrl=====', data)
      let a = document.createElement('a');
      a.href = data;
      a.target = '_blank';
      a.click();
      a = null;
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '结算单号',
          fieldName: 'settleNo',
          disabled: true // 只读
        },
        {
          type: 'INPUT',
          label: '服务站代码',
          fieldName: 'dealerCode',
          disabled: true // 只读
        },
        {
          type: 'INPUT',
          label: '服务站名称',
          fieldName: 'dealerName',
          disabled: true // 只读
        },
        {
          type: 'INPUT',
          label: '结算单类型',
          fieldName: 'finalStatementType',
          disabled: true, // 只读
          itemList: this.createDictList('5002'),
        }
        ,
        {
          type: 'INPUT',
          label: '结算月份',
          fieldName: 'settleDate',
          disabled: true // 只读
        },
        {
          type: 'INPUT_NUMBER',
          label: '结算金额',
          fieldName: 'settleAmount',
          precision: 2, 
          disabled: true // 只读
        }
      ];
    },
    createAuditFormList() {
      return [
        {
          type: 'TEXT_AREA',
          label: '驳回意见',
          fieldName: 'checkRemarks',
          rows:'3',
          maxlength:'200'
          // 只读
        }
      ]
    },
     creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        { title: '车型', dataIndex: 'modelName' },
        // { title: '项目', dataIndex: 'projectName' },
        { title: '首保费用(元)', dataIndex: 'firstServiceMaintenanceCount' , precision: 2, summation: true},
        { title: 'PDI费用(元)', dataIndex: 'pdiCount', precision: 2, summation: true },
        { title: '保修工时费(元)', dataIndex: 'warrantLabourCount', precision: 2, summation: true },
        { title: '合计', dataIndex: 'amount', precision: 2, summation: true }
        //{ title: '合计', dataIndex: '合计' },
      ];
    },

    creatHeaderReport() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '发票类别',
          dataIndex: 'orderType',
          minWidth: 120,
          editable: true,
          defaultEditable: true,
          showOverflowTooltip: true,
          dictItems: this.createDictList('5010'),
          render: props => {
            return <span>{this.createDictText(props.row.orderType, '5010')}</span>;
          }
        //   editRequired: true,
        //   editType: 'select',
        //   editItems: []
        },
        {
          title: '结算比例',
          dataIndex: 'settleRate',
          initialValue: '0',
          
        //   render: props => {
        //     return this.claimRatio(props);
        //   }
        },
        { title: '激励费用(元)', dataIndex: 'businessAmount',precision: 2,  initialValue: '0' },
        { title: '误判金额(元)', dataIndex: 'cbSumAmount', initialValue: '0', precision: 2, summtion: true },
        { title: '运费', dataIndex: 'freightAmount', initialValue: '0', precision: 2, summtion: true },
        {
          title: '开票金额(元)',
          dataIndex: 'invoiceAmount',
          initialValue: '0',
          
          precision: 2,
          //summtion: true
          // render: (props) => {
          //     return this.invoiceMoney(props);
          //   },
        }
        //{ title: '合计', dataIndex: '合计' },
      ];
    },
    creatInvoiceTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 50,
          
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '发票批号',
          dataIndex: 'invoiceBatchNumber',
        },
        {
          title: '发票号码',
          dataIndex: 'invoiceNumber',
        },
        {
          title: '金额(元)',
          dataIndex: 'money',
          precision: 2
        },
        { title: '税率(%)', dataIndex: 'rate',width: 70 },
        { title: '税额(元)', dataIndex: 'taxes',precision: 2},
        {
          title: '合计(元)',
          dataIndex: 'orderAmountSum',
          precision: 2
        //   render: props => {
        //     return this.summation(props);
        //   }
        },
        { title: '开票日期', dataIndex: 'invoiceDate', filterType: 'date-range',  editType: 'date-picker', dateFormat: 'yyyy-MM-dd' }
        //{ title: '合计', dataIndex: '合计' },
      ];
    },
    createdFileTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '附件标题',
          dataIndex: 'title',
          showOverflowTooltip: true,
          render: p => {
            return (
              // <a style="color:#bb0a30" href={p.row.fileUrl} target="_blank" download={p.row.title}>
              //   {p.row.title}
              // </a>
              <div>
                <el-button style="color:#bb0a30" size="mini" type="text" onClick={() => this.downloadFile(p.row.fileUrl)}>
                  {p.row.title}
                </el-button>
              </div>
            );
          }
        },
        {
          title: '上传日期',
          dataIndex: 'createdAt'
        }
      ];
    },
    createdAuditHistoryTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '签收结果',
          dataIndex: 'checkStatus',
          showOverflowTooltip: true,
          dictItems: this.createDictList('5005')
        },
        {
          title: '驳回意见',
          dataIndex: 'checkRemarks',
        },
        {
          title: '签收人',
          dataIndex: 'checkBy',
        },
        { title: '签收时间', dataIndex: 'checkAt'},
      ];
    },
    createLogisticsList() {
      return [
        {
          type: 'INPUT',
          label: '物流/快递公司',
          fieldName: 'logisticsName',
          selfCols:2,
          disabled: true // 只读
        },
        {
          type: 'INPUT',
          label: '物流/快递单号',
          fieldName: 'logisticsNo',
          selfCols:2,
          disabled: true // 只读
        }
      ];
    },
  }
};
</script>
<style lang="less" scoped></style>
